package com.qst.rongxiaotong.controller;

import com.alipay.api.domain.UserDetails;
import com.github.pagehelper.PageInfo;
import com.qst.rongxiaotong.common.Result;
import com.qst.rongxiaotong.common.StatusCode;
import com.qst.rongxiaotong.context.BaseContext;
import com.qst.rongxiaotong.pojo.MyPurchase;
import com.qst.rongxiaotong.pojo.Order;
import com.qst.rongxiaotong.pojo.Purchase;
import com.qst.rongxiaotong.pojo.User;
import com.qst.rongxiaotong.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;

/**
 * @author QST
 * @Description 订单模块
 * @Date 2021-08-24
 */
@Api(tags = "订单模块接口")
@RestController
@RequestMapping("/order")
@CrossOrigin
@Log4j2
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    UserService userService;

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    SellPurchaseService sellPurchaseService;

    //查询所有商品
    @ApiOperation(value = "查询所有商品")
    @GetMapping("/All/{pageNum}")
    public Result<PageInfo> selectAll(@PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectAll(pageNum);
        String currentuserName = BaseContext.getCurrentuserName();
        log.info("登录的用户名为:{}", currentuserName);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }

    //查询所有商品（货源)商品
    @ApiOperation(value = "分页查询所有货源(商品)商品")
    @GetMapping("/goods/{pageNum}")
    public Result<PageInfo> selectAllGoods(@PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectAllGoods(pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }
    //分页条件搜索需求商品
    @ApiOperation(value = "分页条件搜索需求商品")
    @GetMapping("/searchNeedsByKeys/{keys}/{pageNum}")
    public Result<PageInfo> searchNeedsByKeys(@PathVariable("keys") String keys,@PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectNeedsByKeys(keys,pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }

    //分页条件搜索所有商品
    @ApiOperation(value = "分页条件搜索所有商品")
    @GetMapping("/searchAllByKeys/{keys}/{pageNum}")
    public Result<PageInfo> searchAllByKeys(@PathVariable("keys") String keys, @PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectAllByKeys(keys, pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }


    //分页条件搜索商品（货源）商品
    @ApiOperation(value = "分页条件搜索商品（货源）商品")
    @GetMapping("/searchMyGoodsByKeys/{keys}/{pageNum}")
    public Result<PageInfo> searchMyGoodsByKeys(@PathVariable("keys") String keys, @PathVariable("pageNum") Integer pageNum) {

        PageInfo<Order> orders = orderService.selectGoodsByKeys(keys, pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }

    //分页条件搜索商品（货源）商品
    //todo 这个也根据用户名，有点问题
    @ApiOperation(value = "分页条件搜索商品（货源）订单")
    @GetMapping("/searchGoodsByKeys/{keys}/{pageNum}")
    public Result<PageInfo> searchGoodsByKeys(@PathVariable("keys") String keys,@PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectGoodsByKeys(keys,pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }


    //根据id查询商品
    @ApiOperation(value = "根据id查询商品")
    @GetMapping("/selectById/{id}")
    public Result<Order> selectById(@PathVariable("id") Integer id) {
        Order order = orderService.selectById(id);
        return new Result<Order>(true, StatusCode.OK, "查询成功", order);

    }

    //根据用户名+类型查询商品
    @ApiOperation(value = "根据用户名+订单类型查询商品")
    @GetMapping("/search/{type}/{pageNum}")
    public Result<PageInfo> selectByType(@PathVariable("type") String type, @PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectByType(type, pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }

    //添加订单
    @ApiOperation(value = "添加商品")
    @PostMapping
    public Result<String> add(@Valid @RequestBody Order order, BindingResult bindingResult) {
        //检查项目
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            System.out.println(s);
            return new Result<String>(false, StatusCode.ERROR, "添加失败", s);
        }
        //添加
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderService.add(order);
        return new Result(true, StatusCode.OK, "添加成功", null);
    }

    //修改id订单
    @ApiOperation(value = "根据id修改商品")
    @PutMapping("/{id}")
    public Result<String> update(@Validated @RequestBody Order order, BindingResult bindingResult,
                                 @PathVariable Integer id) {
        //检查项目
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            System.out.println(s);
            return new Result<String>(false, StatusCode.ERROR, "修改失败", s);
        }
        order.setOrderId(id);
        orderService.update(order);
        return new Result(true, StatusCode.OK, "修改成功", null);
    }

    //删除订单
    @ApiOperation(value = "根据id删除商品")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        orderService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    //查询所有需求
    @ApiOperation(value = "分页查询所有需求")
    @GetMapping("/needs/{pageNum}")
    public Result<PageInfo> selectAllNeeds(@PathVariable("pageNum") Integer pageNum) {
        PageInfo<Order> orders = orderService.selectAllNeeds(pageNum);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", orders);
    }


    @ApiOperation("/查询个人订单")
    @GetMapping("/selectBuys")
    public Result selectBuys() {
        List<MyPurchase> purchaseList = orderService.selectBuys();
        return new Result<List<MyPurchase>>(true, StatusCode.OK, "查询成功", purchaseList);
    }

    @ApiOperation("/查询个人卖出的订单")
    @GetMapping("/selectSells")
    public Result<List<MyPurchase>> selectSells() {
        List<MyPurchase> purchases = sellPurchaseService.selectSells();
        return new Result<List<MyPurchase>>(true, StatusCode.OK, "查询成功", purchases);
    }
    //TODO 分页条件搜索需求商品--返回值不正确
    @ApiOperation(value = "分页条件搜索需求商品") //接口文档描述
    @GetMapping("/searchMyNeedsByKeys/{keys}/{pageNum}") //请求路径
    public Result<PageInfo> searchMyNeedsByKeys(@PathVariable("keys") String keys,@PathVariable("pageNum") Integer pageNum){
        PageInfo<Order> orderPageInfo = orderService.selectNeedsByKeys(keys, pageNum);
        Result<PageInfo> result = new Result<>(true, StatusCode.OK, "查询成功", orderPageInfo);
        return result;
    }

}